package com.nd.qa.shareplate.controller;

import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import com.nd.qa.shareplate.common.SessionUserInfo;
import com.nd.qa.shareplate.common.SysConstant;
import com.nd.qa.shareplate.model.ApkInfo;
import com.nd.qa.shareplate.model.ShareDocument;
import com.nd.qa.shareplate.service.ManageDocService;
import com.nd.qa.shareplate.util.JsonUtil;

@Controller
@RequestMapping("/manage/*")
public class ManageDocController {

	Logger logger = LoggerFactory.getLogger(APKController.class);
	
	@Autowired
	private ManageDocService manageDocService;
	
	//document_id,document_type,document_name,document_desc,create_time,status
	@SuppressWarnings("unchecked")
	@RequestMapping("/document")
	public String queryTotalDocument(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,Model model,HttpSession session){
		
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		if (sessionUserInfo==null) {
			return "/user/index";
		}
		String userId = sessionUserInfo.getUserId();
		HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
		ShareDocument shareDocument = new ShareDocument();
		Integer totalPages = 0;//总记录数
		Integer currentPage = Integer.valueOf(String.valueOf(inParam.get("currentPage")));
		Integer pageSize = Integer.valueOf(String.valueOf(inParam.get("pageSize")));
		Integer startSize = (currentPage-1)*pageSize;
		try {
			List<ShareDocument> totalDocList = manageDocService.queryTotalDocument(shareDocument);
			if (totalDocList.size()>0&&totalDocList.size()%pageSize==0) {
				totalPages = totalDocList.size()/pageSize;
			}else {
				totalPages = totalDocList.size()/pageSize + 1;
			}
			HashMap<String,Object> paramMap = new HashMap<String,Object>();
			paramMap.put("startSize", startSize);
			paramMap.put("pageSize", pageSize);
			paramMap.put("userId", sessionUserInfo.getUserId());
			List<ShareDocument> documenList = manageDocService.queryDocById(paramMap);
			model.addAttribute("documenList", documenList);
			model.addAttribute("totalPages", totalPages);
		} catch (Exception e) {
			logger.error("查询文档信息异常"+e);
			e.printStackTrace();
		}
		return "/main/document";
	}
	/**
	 * 保存文档信息
	 * @param request
	 * @param response
	 * @param params
	 * @param model
	 * @param session
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/insertDocument")
	public void insertDocument(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,Model model,HttpSession session){
		
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		if (sessionUserInfo==null) {
			resultMap.put("code", "-2");
			resultMap.put("message", "您暂未登录，请先登录");
		}

		//获取入参
		HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
		String documentName = String.valueOf(inParam.get("fileName"));
		String documentVersion = String.valueOf(inParam.get("documentVersion"));
		String documentDesc = String.valueOf(inParam.get("documentDesc"));
		String savePath = String.valueOf(inParam.get("savePath"));
		try {
			savePath = request.getScheme()+"://"+InetAddress.getLocalHost().getHostAddress()+":"+ request.getLocalPort()+request.getContextPath()+savePath;
			//将生成路径入库
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
			String createTime = simpleDateFormat.format(new Date());
			ShareDocument doc = new ShareDocument();
			doc.setDocumentName(documentName);
			doc.setDocumentPath(savePath);
			doc.setDocumentVersion(documentVersion);
			doc.setDocumentDesc(documentDesc);
			doc.setCreateTime(createTime);
			doc.setStatus('A');
			manageDocService.insertDocument(doc);
			resultMap.put("code", "0");
			resultMap.put("message", "保存信息成功");
			response.getWriter().print(JsonUtil.toString(resultMap));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 删除文件信息
	 * @param request
	 * @param response
	 * @param session
	 * @param params
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/deleteDocById")
	public void deleteDocById(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params){
		
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		if (sessionUserInfo==null) {
			resultMap.put("code", "-2");
			resultMap.put("message", "您暂未登录，请先登录");
		}
		response.setCharacterEncoding("UTF-8");
	    response.setContentType("text/html;charset=UTF-8");
	    HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
	    Integer documentId = Integer.valueOf(String.valueOf(inParam.get("documentId")));
	    ShareDocument doc = new ShareDocument();
	    doc.setDocumentId(documentId);
	    try {
	    	manageDocService.deleteDocById(doc);
			resultMap.put("code", "0");
			resultMap.put("message", "删除文件信息成功");
			response.getWriter().print(JsonUtil.toString(resultMap));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
